<?php

namespace App\Http\Controllers\v3;

use App\Models\Records;
use App\Models\Shares;
use App\Models\Videos;
use App\Models\VideosCount;
use App\Models\Views;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 视频相关
 * Class VideoController
 * @package App\Http\Controllers
 */
class VideoController extends Controller {
    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index (Request $request){
        try {
            $params = [
                'chanel_id' => (int)$request->get('chanel_id',0),//频道
                'option' => (int)$request->get('option',1),//推荐
            ];
            $rand = rand(1, 10);
            $lists = Videos::select('id','title','thumb','time','cate_id')
                ->where(function($query) use($params,$rand){
                    if ($params['chanel_id']){
                        $query->where('chanel_id',$params['chanel_id']);
                    }
                    if ($params['option']){
                        $query->where('option',Videos::OPTION_1)->where('rand_cate', $rand);
                    }
                })
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])
                ->orderBy('sort','DESC')
                ->paginate(8);

            return $this->returnJson(0,'',$lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    public function indexTake (Request $request){
        try {
            $params = [
                'chanel_id' => (int)$request->get('chanel_id',0),//频道
                'option' => (int)$request->get('option',1),//推荐
            ];

            $lists = Videos::select('id','title','thumb','time','cate_id')
                ->where(function($query) use($params){
                    if ($params['chanel_id']){
                        $query->where('chanel_id',$params['chanel_id']);
                    }
                    if ($params['option']){
                        $query->where('option',Videos::OPTION_1);
                    }
                })
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])
                ->orderByRaw("RAND()")
                ->orderBy('sort','DESC')
                ->take(50)
                ->get();
            return $this->returnJson(0,'',$lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }
    /**
     * 详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(){
        $openid = request('openid','');
        try {
            $user = $this->getUser($openid);
            $user_id = $user?$user['id']:0;
            $id = request('id',0);
            $shareuid = (int)request('shareuid',0);
            if (empty($id)){
                return $this->returnJson(1,'参数错误');
            }
            $info = Videos::where('status',Videos::STATUS_1)
                ->select('id','title','thumb','time','userid','link','cate_id')
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])
                ->find($id);
            if(!$info){
                return $this->returnJson(1,'数据信息不存在');
            }
            $video = $this->getVideo($info['link']);
            $info['play_link'] = $video['link'];
            //匹配腾讯视频的vid
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $info['link'], $matchs);
            if ($result) {
                $matchs = array_flatten($matchs);
            }
            $vid = $matchs[1] ?? '';
            $info['vid'] = $vid;
            DB::transaction(function () use($id,$info,$user_id,$shareuid){
                //增加视频当天人气记录
                $view = Views::where('video_id',$id)
                    ->whereDate('created_at',Carbon::now()->format('Y-m-d'))
                    ->first();
                if($view){
                    $view->increment('num');
                }else{
                    Views::create([
                        'video_id' => $id,
                        'created_at' => Carbon::now(),
                        'num' => 1
                    ]);
                }
                //增加总人气记录
                $info->increment('view');
                //增加视频统计数据信息
                (new VideosCount())->updateCount($info,'views');   //阅读量
                if($shareuid){

                    $shareData = ['video_id'=>$id,'user_id'=>$user_id];
                    $shareID = Shares::where($shareData)->get()->first();
                    //判断是否是有效分享
                    if(!$shareID && $user_id > 0){
                        //增加视频分享数据信息 in
                        (new VideosCount())->updateCount($info,'share_in');
                        //增加总有效分享数
                        $info->increment('share_count');
                        $shareData['created_at'] = Carbon::now();
                        Shares::create($shareData);
                    }
                }
            });
            return $this->returnJson(0,'success',$info);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    /**
     * 视频播放详情随机列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(){
        try {
            $id = request('id',0);
            if (empty($id)) {
                return $this->returnJson(1, '参数错误');
            }
            $rand = rand(1, 10);
            $lists = Videos::select('id', 'title', 'thumb', 'time', 'view')
                ->where('id', '<>', $id)
                ->where('rand_cate', $rand)
                ->where('status', Videos::STATUS_1)
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name', 'avatar')->get();
                }])
                ->orderBy('sort', 'DESC')
                ->paginate(8);
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    /**
     * 分享
     * @return \Illuminate\Http\JsonResponse
     */
    public function share(){
        $id = (int)request('id');
        if (empty($id)) {
            return $this->returnJson(1, '参数错误');
        }
        $info = Videos::find($id);
        if(!$info){
            return $this->returnJson(1, '数据不存在');
        }
        $info->increment('share');
        //增加视频分享数据信息 out
        (new VideosCount())->updateCount($info,'share_out');
        return $this->returnJson(0);
    }


    public function randList(){
        try {
            $id = (int)request('id');
            if (empty($id)) {
                return $this->returnJson(1, '参数错误');
            }
            $lists = Videos::select('id', 'title', 'thumb', 'time', 'view','cate_id')
                ->where('id', '<>', $id)
                ->where('status', Videos::STATUS_1)
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name', 'avatar')->get();
                }])
                ->take(20)
                ->inRandomOrder()
                ->get();
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    public function staticIndex(){
        return '{"code":0,"msg":"success","data":{"current_page":1,"data":[{"id":6973,"title":"\u53c8\u2014\u4f4d\u660e\u661f\u6ca1\u4e86\uff0c\u5c0f\u71d5\u5b50 \u548c \u7d2b\u8587 \u90fd\u54ed \u4e86 !","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/af69806ed641131cc21ddaecfd9b8a47.","time":"04:27","cate_id":262,"cate":{"id":262,"name":"\u5fc6\u8587","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/a1a9f81d52dadea68c4ae9551eb83e20.jpg"}},{"id":6972,"title":"\u5927\u7237\u4e58\u8f66\uff0c\u65e0\u4eba\u8ba9\u5ea7\uff0c\u7adf\u60f3\u51fa\u5982\u6b64\u7f3a\u5fb7\u62db\u6570","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/c4df836f4242a1762fc3e680682aa147.","time":"02:41","cate_id":339,"cate":{"id":339,"name":"\u7fbd\u9038\u4e4b\u5149","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/9ae1c28729e4ae7cbf142c96f6ee76a7.jpg"}},{"id":6877,"title":"\u4e0a\u5343\u4eba\u5931\u58f0\u75db\u54ed\uff0c\u65e9\u770b\u4e00\u5206\u949f\uff0c\u65e9\u4e00\u5206\u949f\u6094\u609f\uff01","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/2e6465fde370a772fd14c0ef3bb0ff42.","time":"17:32","cate_id":166,"cate":{"id":166,"name":"\u82d7\u82d7","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/8e4617333d2223bc27de080ca7a630cf.jpg"}},{"id":6922,"title":"\u5c0f\u5b69\u7ea2\u70e7\u86c7\u8089\uff0c\u4f60\u6562\u5403\u5417\uff1f\uff1f\uff1f\uff1f\uff1f","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/8796c3e8a1981ee4a51b25cf444fae14.","time":"03:34","cate_id":347,"cate":{"id":347,"name":"\u7ea2\u8587\u67d3\u9732","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/23701038c2f436468d537fb49bd0946c.jpg"}},{"id":6904,"title":"\u5c0f \u4e09,\u5c0f \u4e09,\u5c0f \u4e09\uff0c\u5c0f \u4e09\uff01","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/5449c879281caa9033ba33d87ddcda90.","time":"07:34","cate_id":368,"cate":{"id":368,"name":"\u8c46\u82b1","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/d6e44bf96b614e2b4b22f570a980b29b.jpg"}},{"id":6886,"title":"\u8fd9\u5bf9\u529e\u201c\u79bb\u5a5a\u9152\u201d\u7684\u592b\u59bb\uff0c\u706b\u4e86\uff01","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/c7a1f9b9f84797e22988964357fd7542.","time":"05:15","cate_id":149,"cate":{"id":149,"name":"\u6ee2\u6ee2","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/19e0051934fb4e0735d5e17b449bd7d0.jpg"}},{"id":6849,"title":"\u4e00\u66f2\u60c5\u6b4c\u5bf9\u5531\u300a\u60c5\u5b9a\u4e09\u751f\u300b\u751c\u7f8e\u6781\u4e86\uff0c\u597d\u542c\u6781\u4e86\uff01","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-28\/34bc9c70649bd6a8cc9e2042b781dd33.","time":"04:19","cate_id":116,"cate":{"id":116,"name":"\u683c\u683c","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/5ff8b23a8c876506e1b4a0a0a2beee70.jpg"}},{"id":6736,"title":"\u6c6a\u521a\u4e00\u9996\u300a\u5306\u5306\u90a3\u5e74\u7684\u7f18\u300b\u671d\u671d\u66ae\u66ae\u4e3a\u4f60\u6302\u7275\uff0c\u592a\u4f24\u611f\u4e86\uff01","thumb":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-27\/214c12f31643e8f54ccb58d16f507bb8.","time":"04:10","cate_id":242,"cate":{"id":242,"name":"\u989c\u8bd7\u76c8","avatar":"http:\/\/qiniu.daduiz.xiegangsir.com\/2018-12-13\/d3fe16ea2af2a96d7cec6a4192ca8f80.jpg"}}],"first_page_url":"https:\/\/ash.xiegangsir.com\/api\/v3\/video?page=1","from":1,"last_page":7,"last_page_url":"https:\/\/ash.xiegangsir.com\/api\/v3\/video?page=7","next_page_url":"https:\/\/ash.xiegangsir.com\/api\/v3\/video?page=2","path":"https:\/\/ash.xiegangsir.com\/api\/v3\/video","per_page":8,"prev_page_url":null,"to":8,"total":52}}';
    }
}
